<template>
	<view class="uni-page">
		<cu-custom :isBack="true">
			<block class="bar-font" slot="backText">设备配网</block>
		</cu-custom>
		<view class="page-main">
			<u-steps :list="numList" mode="number" :current="stepValue"></u-steps>
			<view class="main-box">
				<view class="imgs">
					<image src="/static/wifi.png" mode="" class="center_img"></image>
				</view>
				<view class="gundong">
					<view v-if="currents == 0">
						<u-loading mode="flower" size="56"></u-loading>
					</view>
					<view v-else-if="currents == 1">
						<u-icon name="checkmark-circle" size="48" color="#18b566" class="iconst"></u-icon>
					</view>
					<view v-else-if="currents == 2">
						<u-icon name="close-circle" size="48" color="#f29100" class="iconste"></u-icon>
					</view>
					<view class="msg">{{content}}</view>
				</view>
				<view class="buttonst">
					<u-button v-if="currents == 2" type="primary" shape="circle" class="back-btn" @click="linkToWifiForm">重新填写家庭Wi-Fi</u-button>
					<u-button type="primary" shape="circle" plain @click="linkToHome">返回个人中心</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const {
		AppDevSdk
	} = require('qcloud-iotexplorer-appdev-sdk');
	const WifiConfConstants = require('qcloud-iotexplorer-appdev-plugin-wificonf-core').constants;
	const AirKissPlug = require('qcloud-iotexplorer-appdev-plugin-wificonf-airkiss').default;
	
	const {
	  // 步骤code
	  WifiConfStepCode,
	  // 步骤code的中文描述
	  WifiConfStepDesp,
	  // 错误的中文描述
	  WifiConfErrorMsg,
	} = WifiConfConstants;
	
	const onComplete = (deviceInfo) => {
	    console.log('配网完成(onComplete):', deviceInfo);
	    // uni.showModal({
	    // 	content: '配网完成',
	    // 	showCancel: false
	    // });
	};
	
	const onError = async ({ code, detail }) => {
	    const msg = WifiConfErrorMsg[code];
	    console.log('配网错误(onError)', code, msg, detail);
	};

	export default {
		data() {
			return {
				stepValue: 1,
				numList: [{
					name: '配置硬件设备'
				}, {
					name: '设置家庭WiFi'
				}, {
					name: '开始配网'
				}],
				currents: 0,
				result: '',
				buttons: '下一步',
				ind: '',
				jinyong: true,
				targetWifiInfo: {
					SSID: '',
					password: '',
				},
				content: '正在配网（请将设备靠近路由器）……',
				sdk: {},
				accessToken: '',
				bindDeviceToken: ''
			}
		},
		onShow() {
			// 延迟调用配网
			// uni.setTimeout(this.airkiss(), 10000)
		},
		destroyed() {
			wx.stopWifi()
			
		},
		onLoad(options) {
			const $t = this
			// this.wifiName = options.wifiName;
			this.targetWifiInfo = {
				SSID: options.wifiName,
				password: options.pwd
			}
			const sdk = new AppDevSdk({
				debug: true,
				appKey: 'mZFOqyJJeVCaddYzA',
				getAccessToken: this.getAccessToken,
			});
			sdk.usePlugin(AirKissPlug);
			sdk.init()
			AirKissPlug.install(sdk);
			// sdk.init(options) => Promise<void>

			// this.sdk = sdk
			// this.airkiss()
			wx.startWifi()
			sdk.requestApi('AppCreateDeviceBindToken')
				.then((data) => {
					const bindDeviceToken = data.Token;
					this.bindDeviceToken = bindDeviceToken
					console.log('wifi设备配网Token=', bindDeviceToken);
					sdk.plugins['wifiConfAirKiss'].start({
						wifiConfToken: 'bindDeviceToken',
						targetWifiInfo: this.targetWifiInfo,
						autoRetry: true, // 自动处理故障流程
						familyId: 'default',
						roomId: '1',
						onProgress: $t.onProgress,
						onComplete,
						onError
					});
				});
		},
		methods: {
			onProgress( val ) {
				const msg = WifiConfStepDesp[val.code];
				console.log('配网步骤更新_(onProgress)', val.code, msg, val.detail)
				switch (val.code) {
				    case WifiConfStepCode.PROTOCOL_SUCCESS: // 结束配网
						this.currents = 1
						this.stepValue = 2
						this.content = '配网成功'
						break;
				  //   case WifiConfStepCode.CREATE_UDP_CONNECTION_SUCCESS:
						// this.content = msg
						// break;
				    case WifiConfStepCode.WIFI_CONF_FAIL:
						if (val.detail && val.detail.error && val.detail.error.code === 'PROTOCOL_TIMEOUT') {
							this.currents = 2
							this.content = '配网失败，请检查设备和网络后重试'
						}
						break;
				 //  case WifiConfStepCode.BUSINESS_QUERY_TOKEN_STATE_SUCCESS:
					// this.content = msg
					// break;
				 //  case WifiConfStepCode.WIFI_CONF_SUCCESS:
					// this.content = msg
					// break;
				}
			},
			linkToHome () {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			},
			linkToWifiForm () {
				uni.navigateTo({
					url: '/pages/configWiFi/formpage/formpage'
				})
			},
			async getAccessToken () {
				// 获取小程序登录凭证（code）
				const code = await new Promise((resolve, reject) => {
					wx.login({
						success: (res) => resolve(res.code),
						fail: reject
					});
				});
			
				// 获取小程序用户信息
				const userInfo = await new Promise((resolve, reject) => {
					wx.getUserInfo({
						success: (res) => resolve(res.userInfo),
						fail: reject
					});
				});
			
				// 调用开发者自建的后台服务端获取 AccessToken
				// 请根据实际情况调整实现
				const { appId } = uni.getAccountInfoSync().miniProgram
				const resp = await this.$http.post('/txcloud/appGetTokenByWeiXin', {
					code: code,
					appid: appId,
					userInfo: userInfo
				}).then(res => {
					console.log('token', res.content)
					return res.content
				})

				return {
					Token: resp,
					ExpireAt: 7200,
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uni-page {
		height: 100vh;
		background-color: #FFFFFF;
	}
	.page-main {
		padding-top: 40rpx;
		.main-box {
			padding: 60rpx 40rpx 0;
		}
	}
	.center_img {
		width: 280rpx;
		height: 280rpx;
		margin: 100rpx auto 80rpx;
	}

	.imgs {
		display: flex;
	}

	.gundong {
		display: flex;
		align-items: center;
		justify-content: center;
		.msg {
			font-size: 30rpx;
		}
	}

	.buttonst {
		margin: 120rpx 60rpx 0;
	}
	
	.back-btn {
		display: block;
		margin-bottom: 40rpx;
	}

	.div_top {
		height: 300px;
	}
	.iconst {
		padding: 5px;
	}

	.iconste {
		padding: 5px;
	}
</style>
